/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 2015-1-29, 15:53:31
 */

package org.feichao.wordinspector;

import java.io.File;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.text.StyledDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import org.feichao.wordinspector.beans.DocumentNode;

/**
 *
 * @author chao
 */
public class MainFrame extends javax.swing.JFrame {
    
    Model model ;

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        model = new Model(this);

        DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode("打开文件");
        DefaultTreeModel treeModel = new DefaultTreeModel(rootTreeNode);
        documentTree.setModel(treeModel);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        menuBar1 = new java.awt.MenuBar();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        documentTree = new javax.swing.JTree();
        nodeInfoPane1 = new org.feichao.wordinspector.ui.NodeInfoPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        openFileMenuItem = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jSplitPane1.setDividerLocation(200);

        documentTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                documentTreeMouseClicked(evt);
            }
        });
        documentTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                documentTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(documentTree);

        jSplitPane1.setLeftComponent(jScrollPane1);
        jSplitPane1.setRightComponent(nodeInfoPane1);

        jMenu1.setText("文件");

        openFileMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        openFileMenuItem.setText("打开Word");
        openFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openFileMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(openFileMenuItem);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("更多");

        aboutMenuItem.setText("关于");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        jMenu2.add(aboutMenuItem);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 999, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFileMenuItemActionPerformed
        // TODO add your handling code here:

        JFileChooser fileChooser = new JFileChooser();

        int result = fileChooser.showOpenDialog(this);
        if(result == JFileChooser.APPROVE_OPTION){
                File doc = fileChooser.getSelectedFile();
                List<DocumentNode> nodes = model.processFile(doc);
                DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode(doc.getName());
                DefaultTreeModel treeModel = new DefaultTreeModel(rootTreeNode);
                for(DocumentNode dn: nodes){
                     appendTreeNode(rootTreeNode, dn);
                }
                documentTree.setModel(treeModel);
        }
        
    }//GEN-LAST:event_openFileMenuItemActionPerformed

    private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
        // TODO add your handling code here:
        JOptionPane.showMessageDialog(null, "Word文件结构解析器 \n-作者steven0lisa", "关于", JOptionPane.INFORMATION_MESSAGE);

    }//GEN-LAST:event_aboutMenuItemActionPerformed

    private void documentTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_documentTreeValueChanged
        // TODO add your handling code here:
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) documentTree.getLastSelectedPathComponent();
        if(node != null){
            Object data = node.getUserObject();
            if(data instanceof DocumentNode){
            DocumentNode documentNode = (DocumentNode)data;
            if(documentNode.content.contains("[img]")){
                StyledDocument doc = null;
                nodeInfoPane1.getJtextPane().setText("");
                int index = 0;
                int beginIndex = 0;
                int endIndex = 0;
                while(index >=0 && beginIndex>=0 && endIndex >=0){
                    beginIndex = documentNode.content.indexOf("[img]",index)+5;
                    endIndex = documentNode.content.indexOf("[/img]",index);
                    if(beginIndex >0 && endIndex>0 &&beginIndex < endIndex){
                        String filePath = documentNode.content.substring(beginIndex,endIndex);
                        doc = nodeInfoPane1.getJtextPane().getStyledDocument();
                        try{
                            doc.insertString(doc.getLength(),documentNode.content.substring(index,beginIndex-5)+"\r\n", null);
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                        ImageIcon  icon = new ImageIcon(ConstVariables.imagePath+filePath);
                        nodeInfoPane1.getJtextPane().setCaretPosition(doc.getLength());
                        nodeInfoPane1.getJtextPane().insertIcon(icon);
                        index = endIndex+6;
                    }
                }
            }else{
                nodeInfoPane1.getJtextPane().setText(documentNode.content);
            }
            nodeInfoPane1.getJlabel2().setText(documentNode.type);
        }
        }
        
}//GEN-LAST:event_documentTreeValueChanged

    private void documentTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_documentTreeMouseClicked
        // TODO add your handling code here:

    }//GEN-LAST:event_documentTreeMouseClicked


    void appendTreeNode(DefaultMutableTreeNode treeNode, DocumentNode docDcoumentNode){
        DefaultMutableTreeNode currTreeNode = new DefaultMutableTreeNode(docDcoumentNode);
        treeNode.add(currTreeNode);
        for(DocumentNode dn: docDcoumentNode.children){
            appendTreeNode(currTreeNode, dn);
        }

    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JTree documentTree;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private java.awt.MenuBar menuBar1;
    private org.feichao.wordinspector.ui.NodeInfoPane nodeInfoPane1;
    private javax.swing.JMenuItem openFileMenuItem;
    // End of variables declaration//GEN-END:variables

}
